#ifndef _IO_TIMER_H_
#define _IO_TIMER_H_

#include <ioeventdef.h>

class IoTimer
{
public:
	IoTimer(void) {

		second = 0;
		stat = S_ERROR;
		this->tm = NULL;
		this->safe = NULL;
	}
	virtual ~IoTimer(void) {
		
		time_destory();
	}
	int time_create(io_service* pService) {

		this->tm = ALLOC_NEW io_time(*pService);
		rc_assert(this->tm, S_ERROR)

		return S_SUCCESS;
	}
	int time_destory() {

		rc_assert(this->tm, S_ERROR)
		delete this->tm;
		this->tm = NULL;

		return S_SUCCESS;
	}

	int time_sec(int sec) {

		rc_assert(this->tm, S_ERROR)
		int rc = S_SUCCESS;

		try {
			this->tm->expires_from_now(boost::posix_time::seconds(sec));
			second = sec;
		} catch (stdexcep err) {
			loge("std::exception:%s", err.what());
			rc = S_ERROR;
		}
		return S_SUCCESS;
	}
	int time_start() {

		rc_assert(this->tm, S_ERROR)
		int rc = S_SUCCESS;

		try {
			this->tm->async_wait(boost::bind(&IoTimer::timer_handler,
				this,
				boost::asio::placeholders::error));

			stat = S_SUCCESS;

		} catch (stdexcep err) {
			loge("std::exception:%s", err.what());
			rc = S_ERROR;
		}
		return rc;
	}
	int time_stop() {

		rc_assert(this->tm, S_ERROR)
		int rc = S_SUCCESS;

		try {
			this->tm->cancel();
			stat = S_ERROR;
		}
		catch (stdexcep err) {
			loge("std::exception:%s", err.what());
			rc = S_ERROR;
		}

		return S_SUCCESS;
	}
	int time_contine() {

		rc_assert(this->tm, S_ERROR)
		int rc = S_SUCCESS;

		try {
			this->tm->expires_from_now(boost::posix_time::seconds(second));
			this->tm->async_wait(boost::bind(&IoTimer::timer_handler,
				this,
				boost::asio::placeholders::error));
		} catch (stdexcep err) {
			loge("std::exception:%s", err.what());
			rc = S_ERROR;
		}
		return S_SUCCESS;
	}

	int timer_handler(io_c_error_code ec) {

		if (ec) {
			if (ec.value() != boost::system::errc::operation_canceled) {
				//this->OnTime(S_ERROR);
			}
		} else {
			this->OnTime(S_SUCCESS);
		}
		return S_SUCCESS;
	}
public:
	virtual int OnTime(UINT err) = 0;


private:
	int second;
	int stat;
	io_time_ptr	tm;
	io_strand_ptr safe;
};

#endif


